package com.bwie.client;


import com.alibaba.fastjson.JSON;
import com.bwie.message.BaseMessage;
import com.bwie.protocol.CustomProtocol;
import com.bwie.util.JT808Const;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * TCP客户端处理器，负责处理消息发送和接收
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class TcpClientHandler extends SimpleChannelInboundHandler<CustomProtocol> {
    private static final Logger logger = LoggerFactory.getLogger(TcpClientHandler.class);

    // 存储待发送的消息
    private String message;

    public TcpClientHandler() {
    }

    /**
     * 当客户端与服务器建立连接后调用
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        logger.info("客户端已连接到服务器，准备发送消息");

//        message = "hello,world";

        // 发送消息，会被CustomEncoder自动加上0x7e首尾标识
//        ctx.writeAndFlush(new CustomProtocol("hello,world".getBytes()));
    }

    /**
     * 当收到服务器返回的消息时调用
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, CustomProtocol msg) {
        String message = new String(msg.getContent(), StandardCharsets.UTF_8);
        logger.info("客户端收到服务器响应: {}", message);

        BaseMessage baseMessage = JSON.parseObject(message, BaseMessage.class);
        switch (baseMessage.getMessageId()) {
            case JT808Const.SERVER_RESP_REGISTER:
                handleRegisterMessage(ctx, message);
                break;
        }

    }

    /**
     * 发生异常时调用
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        logger.error("客户端发生异常", cause);
        ctx.close();
    }

    /**
     * 连接断开时调用
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        logger.info("与服务器的连接已断开");
    }

    public void handleRegisterMessage(ChannelHandlerContext ctx, String message) {
        logger.info("收到服务器注册确认消息：{}", message);
    }
}

